<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>提示词模板管理 - 盖世数据智能分析平台</title>
    <!-- 固定样式引入 - 不可修改路径 -->
    <!-- 引入React和ReactDOM -->
    <script src="/libs/react.development.js"></script>
    <script src="/libs/react-dom.development.js"></script>

    <!-- 引入Material-UI核心依赖 -->
    <script src="/libs/material-ui.development.js"></script>
    <script src="/libs/emotion-react.umd.min.js"></script>
    <script src="/libs/emotion-styled.umd.min.js"></script>

    <!-- 引入Babel用于解析JSX -->
    <script src="/libs/babel.min.js"></script>

    <!-- 引入Material图标（可选） -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="/pages/app.css">
</head>

<body>
    <div id="root"></div>

    <!-- 固定脚本引入 - 不可修改路径 -->
    <script type="text/babel" data-type="module">
        // 固定核心库引入, client.js?{token} token 是32位，你的任何调整都会导致类库加载失败
        import iToolX, { iUpload, iUtils, iEmit } from "http://editor.aibot.gasgoo.com/editor-ui/client.js?a72dfc24ac69ccae7cf363c09e192c19";
        import clientState from "/pages/clientState.js";

        // 从MUI导入所需组件
        const { 
            Button, 
            Card, 
            CardContent, 
            CardHeader, 
            Typography,
            TextField,
            Select,
            MenuItem,
            FormControl,
            InputLabel,
            Table,
            TableBody,
            TableCell,
            TableContainer,
            TableHead,
            TableRow,
            Paper,
            IconButton,
            Dialog,
            DialogTitle,
            DialogContent,
            DialogActions,
            Pagination,
            Box,
            Grid,
            Chip,
            Alert,
            Snackbar,
            Tabs,
            Tab,
            Divider
        } = MaterialUI;

        // 创建React组件
        function App() {
            // 状态管理
            const [templates, setTemplates] = React.useState([]);
            const [loading, setLoading] = React.useState(false);
            const [page, setPage] = React.useState(1);
            const [pageSize, setPageSize] = React.useState(10);
            const [total, setTotal] = React.useState(0);
            const [filters, setFilters] = React.useState(clientState.getTemplateFilters());
            const [openDialog, setOpenDialog] = React.useState(false);
            const [editingTemplate, setEditingTemplate] = React.useState(null);
            const [formData, setFormData] = React.useState({
                name: '',
                content: '',
                description: ''
            });
            const [snackbar, setSnackbar] = React.useState({
                open: false,
                message: '',
                severity: 'success'
            });
            const [openTestDialog, setOpenTestDialog] = React.useState(false);
            const [selectedTemplate, setSelectedTemplate] = React.useState(null);
            const [testInput, setTestInput] = React.useState('');
            const [testResult, setTestResult] = React.useState('');
            const [testLoading, setTestLoading] = React.useState(false);
            const [tabValue, setTabValue] = React.useState(0);

            // 获取模板列表
            const fetchTemplates = React.useCallback(async () => {
                setLoading(true);
                try {
                    const response = await iToolX.modules.promptTemplateManager.getTemplateList(
                        filters.keyword,
                        page,
                        pageSize
                    );
                    
                    if (response.code !== 200) {
                        throw new Error(response.message);
                    }
                    
                    setTemplates(response.data.list);
                    setTotal(response.data.total);
                } catch (error) {
                    console.error('获取模板列表失败:', error);
                    setSnackbar({
                        open: true,
                        message: `获取模板列表失败: ${error.message}`,
                        severity: 'error'
                    });
                } finally {
                    setLoading(false);
                }
            }, [filters.keyword, page, pageSize]);

            // 初始化加载
            React.useEffect(() => {
                fetchTemplates();
            }, [fetchTemplates]);

            // 保存筛选条件
            React.useEffect(() => {
                clientState.setTemplateFilters(filters);
            }, [filters]);

            // 处理筛选条件变化
            const handleFilterChange = (field, value) => {
                setFilters(prev => ({
                    ...prev,
                    [field]: value
                }));
                setPage(1); // 重置页码
            };

            // 打开添加模板对话框
            const handleAddTemplate = () => {
                setEditingTemplate(null);
                setFormData({
                    name: '',
                    content: '',
                    description: ''
                });
                setOpenDialog(true);
            };

            // 打开编辑模板对话框
            const handleEditTemplate = (template) => {
                setEditingTemplate(template);
                setFormData({
                    name: template.name,
                    content: template.content,
                    description: template.description
                });
                setOpenDialog(true);
            };

            // 保存模板
            const handleSaveTemplate = async () => {
                try {
                    // 验证表单
                    if (!formData.name.trim()) {
                        setSnackbar({
                            open: true,
                            message: '请输入模板名称',
                            severity: 'warning'
                        });
                        return;
                    }
                    
                    if (!formData.content.trim()) {
                        setSnackbar({
                            open: true,
                            message: '请输入模板内容',
                            severity: 'warning'
                        });
                        return;
                    }
                    
                    let response;
                    if (editingTemplate) {
                        // 更新模板
                        response = await iToolX.modules.promptTemplateManager.updateTemplate(
                            editingTemplate.id,
                            formData.name.trim(),
                            formData.content.trim(),
                            formData.description.trim()
                        );
                    } else {
                        // 添加模板
                        response = await iToolX.modules.promptTemplateManager.addTemplate(
                            formData.name.trim(),
                            formData.content.trim(),
                            formData.description.trim()
                        );
                    }
                    
                    if (response.code !== 200) {
                        throw new Error(response.message);
                    }
                    
                    setOpenDialog(false);
                    setSnackbar({
                        open: true,
                        message: editingTemplate ? '模板更新成功' : '模板添加成功',
                        severity: 'success'
                    });
                    fetchTemplates();
                } catch (error) {
                    console.error('保存模板失败:', error);
                    setSnackbar({
                        open: true,
                        message: `保存模板失败: ${error.message}`,
                        severity: 'error'
                    });
                }
            };

            // 删除模板
            const handleDeleteTemplate = async (id) => {
                if (!window.confirm('确定要删除此模板吗？')) {
                    return;
                }
                
                try {
                    const response = await iToolX.modules.promptTemplateManager.deleteTemplate(id);
                    
                    if (response.code !== 200) {
                        throw new Error(response.message);
                    }
                    
                    setSnackbar({
                        open: true,
                        message: '模板删除成功',
                        severity: 'success'
                    });
                    fetchTemplates();
                } catch (error) {
                    console.error('删除模板失败:', error);
                    setSnackbar({
                        open: true,
                        message: `删除模板失败: ${error.message}`,
                        severity: 'error'
                    });
                }
            };

            // 打开测试Prompt对话框
            const handleOpenTestDialog = (template) => {
                setSelectedTemplate(template);
                setTestInput('');
                setTestResult('');
                setOpenTestDialog(true);
                setTabValue(0); // 重置到输入数据标签页
            };

            // 测试Prompt
            const handleTestPrompt = async () => {
                if (!testInput.trim()) {
                    setSnackbar({
                        open: true,
                        message: '请输入测试数据',
                        severity: 'warning'
                    });
                    return;
                }
                
                setTestLoading(true);
                try {
                    // 组合模板内容和用户输入
                    const combinedPrompt = `${selectedTemplate.content}\n\n用户输入：${testInput}`;
                    
                    // 执行AI流程
                    const response = await iToolX.flows.crawl(combinedPrompt);
                    
                    setTestResult(response);
                    setTabValue(1); // 切换到结果标签页
                } catch (error) {
                    console.error('测试Prompt失败:', error);
                    setSnackbar({
                        open: true,
                        message: `测试Prompt失败: ${error.message}`,
                        severity: 'error'
                    });
                } finally {
                    setTestLoading(false);
                }
            };

            // 关闭提示框
            const handleCloseSnackbar = () => {
                setSnackbar(prev => ({ ...prev, open: false }));
            };

            // 处理分页变化
            const handlePageChange = (event, newPage) => {
                setPage(newPage);
            };

            // 处理表单字段变化
            const handleFormChange = (field, value) => {
                setFormData(prev => ({
                    ...prev,
                    [field]: value
                }));
            };

            // 处理标签页变化
            const handleTabChange = (event, newValue) => {
                setTabValue(newValue);
            };

            return (
                <div className="page-wrapper">
                    {/* 顶部导航 */}
                    <header className="header">
                        <div className="container nav-container">
                            <a href="/pages/home.html" className="logo">
                                <div className="logo-icon">C</div>
                                <span>盖世数据智能分析平台</span>
                            </a>
                            
                            <nav>
                                <ul className="nav-menu">
                                    <li className="nav-item">
                                        <a href="/pages/home.html" className="nav-link">首页</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/sources.html" className="nav-link">抓取源</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/contentManagement.html" className="nav-link">抓取内容</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/analysisList.html" className="nav-link">抓取内容分析</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/promptTemplateManagement.html" className="nav-link active">提示词管理</a>
                                    </li>
                                    <li className="nav-item">
                                        <a href="/pages/business/contentPoolManagement.html" className="nav-link">内容池管理</a>
                                    </li>
                                </ul>
                            </nav>
                            
                            <div className="nav-actions">
                                <div className="search-box">
                                    <span className="material-icons search-icon">search</span>
                                    <input 
                                        type="text" 
                                        className="search-input" 
                                        placeholder="搜索模板..."
                                        value={filters.keyword}
                                        onChange={(e) => handleFilterChange('keyword', e.target.value)}
                                    />
                                </div>
                            </div>
                        </div>
                    </header>

                    {/* 主体内容 */}
                    <main className="main-content">
                        <div className="container">
                            {/* 页面标题和操作按钮 */}
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                                <Typography variant="h4" component="h1">提示词模板管理</Typography>
                                <Button 
                                    variant="contained" 
                                    startIcon={<span className="material-icons">add</span>}
                                    onClick={handleAddTemplate}
                                >
                                    添加模板
                                </Button>
                            </div>

                            {/* 模板搜索模块 */}
                            <Card style={{ marginBottom: '20px' }}>
                                <CardContent>
                                    <Grid container spacing={2}>
                                        <Grid item xs={12} sm={8}>
                                            <TextField
                                                label="搜索模板"
                                                fullWidth
                                                value={filters.keyword}
                                                onChange={(e) => handleFilterChange('keyword', e.target.value)}
                                                placeholder="搜索名称、描述或内容..."
                                                margin="normal"
                                            />
                                        </Grid>
                                        <Grid item xs={12} sm={4} style={{ display: 'flex', alignItems: 'center' }}>
                                            <Button 
                                                variant="outlined" 
                                                onClick={() => {
                                                    setFilters({ keyword: '' });
                                                    setPage(1);
                                                }}
                                                style={{ marginTop: '16px' }}
                                            >
                                                重置搜索
                                            </Button>
                                        </Grid>
                                    </Grid>
                                </CardContent>
                            </Card>

                            {/* 模板列表模块 */}
                            <Card>
                                <CardContent>
                                    {loading ? (
                                        <div className="loading">
                                            <div className="loading-spinner"></div>
                                        </div>
                                    ) : templates.length === 0 ? (
                                        <div className="empty-state">
                                            <span className="material-icons empty-icon">description</span>
                                            <div className="empty-text">暂无模板数据</div>
                                            <Button 
                                                variant="contained" 
                                                startIcon={<span className="material-icons">add</span>}
                                                onClick={handleAddTemplate}
                                            >
                                                添加第一个模板
                                            </Button>
                                        </div>
                                    ) : (
                                        <>
                                            <TableContainer component={Paper}>
                                                <Table>
                                                    <TableHead>
                                                        <TableRow>
                                                            <TableCell>名称</TableCell>
                                                            <TableCell>描述</TableCell>
                                                            <TableCell>创建时间</TableCell>
                                                            <TableCell>操作</TableCell>
                                                        </TableRow>
                                                    </TableHead>
                                                    <TableBody>
                                                        {templates.map((template) => (
                                                            <TableRow key={template.id}>
                                                                <TableCell>{template.name}</TableCell>
                                                                <TableCell>{template.description || '无描述'}</TableCell>
                                                                <TableCell>
                                                                    {new Date(template.create_at).toLocaleString()}
                                                                </TableCell>
                                                                <TableCell>
                                                                    <IconButton 
                                                                        size="small" 
                                                                        onClick={() => handleEditTemplate(template)}
                                                                        title="编辑"
                                                                    >
                                                                        <span className="material-icons">edit</span>
                                                                    </IconButton>
                                                                    <IconButton 
                                                                        size="small" 
                                                                        onClick={() => handleOpenTestDialog(template)}
                                                                        title="测试Prompt"
                                                                    >
                                                                        <span className="material-icons">play_arrow</span>
                                                                    </IconButton>
                                                                    <IconButton 
                                                                        size="small" 
                                                                        onClick={() => handleDeleteTemplate(template.id)}
                                                                        title="删除"
                                                                    >
                                                                        <span className="material-icons">delete</span>
                                                                    </IconButton>
                                                                </TableCell>
                                                            </TableRow>
                                                        ))}
                                                    </TableBody>
                                                </Table>
                                            </TableContainer>
                                            
                                            {/* 分页 */}
                                            <div style={{ display: 'flex', justifyContent: 'center', marginTop: '20px' }}>
                                                <Pagination 
                                                    count={Math.ceil(total / pageSize)} 
                                                    page={page} 
                                                    onChange={handlePageChange} 
                                                    color="primary" 
                                                />
                                            </div>
                                        </>
                                    )}
                                </CardContent>
                            </Card>
                        </div>
                    </main>

                    {/* 页脚 */}
                    <footer className="footer">
                        <div className="container footer-content">
                            <ul className="footer-links">
                                <li><a href="#">关于我们</a></li>
                                <li><a href="#">使用指南</a></li>
                                <li><a href="#">隐私政策</a></li>
                                <li><a href="#">联系我们</a></li>
                            </ul>
                            <div className="footer-copyright">
                                ? 2023 盖世数据智能分析平台 - 保留所有权利
                            </div>
                        </div>
                    </footer>

                    {/* 模板编辑模块 */}
                    <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="xl" fullWidth>
                        <DialogTitle>
                            {editingTemplate ? '编辑模板' : '添加模板'}
                        </DialogTitle>
                        <DialogContent>
                            <Grid container spacing={3}>
                                {/* 左侧：基本信息 */}
                                <Grid item xs={12} md={4}>
                                    <Typography variant="h6" gutterBottom>基本信息</Typography>
                                    <TextField
                                        label="模板名称"
                                        fullWidth
                                        value={formData.name}
                                        onChange={(e) => handleFormChange('name', e.target.value)}
                                        margin="normal"
                                        required
                                    />
                                    <TextField
                                        label="描述"
                                        fullWidth
                                        multiline
                                        rows={4}
                                        value={formData.description}
                                        onChange={(e) => handleFormChange('description', e.target.value)}
                                        margin="normal"
                                        placeholder="简要描述此模板的用途..."
                                    />
                                    <Box sx={{ mt: 3 }}>
                                        <Typography variant="body2" color="text.secondary">
                                            <strong>提示：</strong>模板内容可以使用占位符，如 {`{主题}`}、{`{关键词}`} 等，在生成时会被替换为实际内容。
                                        </Typography>
                                    </Box>
                                </Grid>
                                
                                {/* 右侧：模板内容编辑区域 */}
                                <Grid item xs={12} md={8}>
                                    <Typography variant="h6" gutterBottom>模板内容</Typography>
                                    <TextField
                                        label="模板内容"
                                        fullWidth
                                        multiline
                                        rows={20}
                                        value={formData.content}
                                        onChange={(e) => handleFormChange('content', e.target.value)}
                                        margin="normal"
                                        required
                                        placeholder="请输入提示词模板内容，例如：请根据以下分析结果生成一篇关于{主题}的文章..."
                                        variant="outlined"
                                        InputProps={{
                                            style: { fontFamily: 'monospace', fontSize: '14px' }
                                        }}
                                    />
                                </Grid>
                            </Grid>
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => setOpenDialog(false)}>取消</Button>
                            <Button 
                                onClick={handleSaveTemplate} 
                                variant="contained" 
                                disabled={!formData.name.trim() || !formData.content.trim()}
                            >
                                保存
                            </Button>
                        </DialogActions>
                    </Dialog>

                    {/* 测试Prompt对话框 */}
                    <Dialog open={openTestDialog} onClose={() => setOpenTestDialog(false)} maxWidth="md" fullWidth>
                        <DialogTitle>测试Prompt</DialogTitle>
                        <DialogContent>
                            {selectedTemplate && (
                                <Box sx={{ mb: 2 }}>
                                    <Typography variant="subtitle1">模板: {selectedTemplate.name}</Typography>
                                </Box>
                            )}
                            
                            <Tabs value={tabValue} onChange={handleTabChange}>
                                <Tab label="输入数据" />
                                <Tab label="测试结果" />
                            </Tabs>
                            
                            {tabValue === 0 && (
                                <Box sx={{ mt: 2 }}>
                                    <TextField
                                        label="测试数据"
                                        fullWidth
                                        multiline
                                        rows={10}
                                        value={testInput}
                                        onChange={(e) => setTestInput(e.target.value)}
                                        margin="normal"
                                        placeholder="请输入测试数据，系统将结合模板内容执行AI流程..."
                                    />
                                </Box>
                            )}
                            
                            {tabValue === 1 && (
                                <Box sx={{ mt: 2 }}>
                                    {testResult ? (
                                        <Paper variant="outlined" sx={{ p: 2, maxHeight: '400px', overflow: 'auto' }}>
                                            <Typography variant="body1" style={{ whiteSpace: 'pre-wrap' }}>
                                                {testResult}
                                            </Typography>
                                        </Paper>
                                    ) : (
                                        <Typography variant="body2" color="text.secondary">
                                            尚未生成测试结果，请先在"输入数据"标签页输入测试数据并点击测试按钮
                                        </Typography>
                                    )}
                                </Box>
                            )}
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={() => setOpenTestDialog(false)}>关闭</Button>
                            {tabValue === 0 && (
                                <Button 
                                    onClick={handleTestPrompt} 
                                    variant="contained"
                                    disabled={!testInput.trim() || testLoading}
                                >
                                    {testLoading ? '测试中...' : '测试Prompt'}
                                </Button>
                            )}
                        </DialogActions>
                    </Dialog>

                    {/* 提示信息 */}
                    <Snackbar
                        open={snackbar.open}
                        autoHideDuration={6000}
                        onClose={handleCloseSnackbar}
                    >
                        <Alert 
                            onClose={handleCloseSnackbar} 
                            severity={snackbar.severity} 
                            sx={{ width: '100%' }}
                        >
                            {snackbar.message}
                        </Alert>
                    </Snackbar>
                </div>
            );
        }

        // 渲染组件到页面
        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(<App />);
    </script>
</body>

</html>